package com.anjie.powerproject.service.impl;

import com.anjie.powerproject.common.MockDataUtil;
import com.anjie.powerproject.entity.PreStrategy;
import com.anjie.powerproject.entity.StrategyOutput;
import com.anjie.powerproject.repository.StrategyOutputRepository;
import com.anjie.powerproject.service.StrategyOutputService;
import com.anjie.powerproject.strategy.utils.DateUtils;
import com.anjie.powerproject.util.DateRange;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.env.Environment;
import org.springframework.stereotype.Service;

import java.util.*;
import java.util.stream.Collectors;

@Service
public class StrategyOutputServiceImpl implements StrategyOutputService {

    @Autowired
    StrategyOutputRepository strategyOutputRepository;

    @Autowired
    MockDataUtil mockDataUtil;

    @Autowired
    Environment env;

    @Override
    public List<List<StrategyOutput>> getStrategyOutputByCodeAndDateRange(Integer code, Date startTime, Date endTime,Integer strategyType) {
        if (Arrays.asList(env.getActiveProfiles()).contains("dev")) {
            return mockDataUtil.buildStrategyOutputList(startTime, endTime);
        }

        Date limitDate = DateUtils.plusOrMinusDay(endTime, 1).getTime();
        String start = DateUtils.ymdFormat.format(startTime);
        String end = DateUtils.ymdFormat.format(limitDate);

//        List<StrategyOutput> strategyOutputs = strategyOutputRepository.getStrategyOutput(start, end);
        List<StrategyOutput> strategyOutputs = strategyOutputRepository.getStrategyOutputByDateAndType(start, end, strategyType);
        List<String> dateList = DateRange.getDateListOfDateRange(startTime, endTime);

        Map<String, List<StrategyOutput>> strategyOutputMap = strategyOutputs.stream().collect(Collectors.groupingBy(e -> DateUtils.ymdFormat.format(e.getStartTime())));

        List<List<StrategyOutput>> strategyOutputList = new ArrayList<>();
        for (String date : dateList) {
            strategyOutputList.add(strategyOutputMap.get(date));
        }

        return strategyOutputList;
    }

    @Override
    public List<StrategyOutput> getStrategyOutputByDate(Date time) {
        String timeStr = DateUtils.ymdFormat.format(time);
        return strategyOutputRepository.getStrategyOutputByDate(timeStr);
    }

    @Override
    public List<Float> getPowerInStrategy(Integer deviceId, Integer limit) {
        return strategyOutputRepository.getPowerListByDeviceId(deviceId, limit);
    }

    @Override
    public void save(StrategyOutput strategy) {
        strategyOutputRepository.saveAndFlush(strategy);
    }
}
